%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% O-Ring Production Networks
%   Author: Demir, Fieler, Xu, Yang
%   Last updated: December 2021
%   Purpose: Model with Import
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
close all; diary off; clc; clear;   


%% Parameters
   
    define_param 
    
    %calibrated parameters
    param.kappa     = 8.6845e-04;   %matching friction
    param.nu_v      = 3.0948;       %sd of directed search
    param.nu_y      = 0.3506;       %complementarity

    param.omega1_sd = 0.1158;       %sd of omega1
    param.omega0_sd = 0.1102;       %sd of omega0
    param.omega_rho = 0.1372;       %correlation
    param.omega2    = -0.1031;      %omega2 
   
    param.mu_E      = -3.9514;      %mean of log export cost
    param.sigma_E   = 1.5200;       %sd of log export cost
    param.b1        = 93.1595;      %foreign demand shifter
    param.b2        = 0.4931;       %foreign demand curvature
 
    param.mu_I      = -5.5;
    param.sigma_I   = 1.5200;
    param.b3        = 26;
    param.b4        = -0.105;


%% Initial Equilibrium
fprintf('\nInitial Equilibrium\n');

    % data moment
    define_data_moment
    
    % constants
    define_omega_dist 
    define_const     

    % solve initial equilibrium
    eqm = solve_eqm_outer(param, const);    
    define_wage_schedule 
    
    % calculate model moments and objfcn
    model = cal_model_moment(param, const, eqm);     
    bartik = cal_chg_bartik(param, const, eqm);     

    % calculate vars for each firm type
    firm = cal_firm_vars(param, const, eqm);    


    
%% 5 Percent Export Demand Shock

    const.D_F = param.shock*const.D_F;
    
    
%% Baseline Counterfactual  
fprintf('\nBaseline Counterfactual\n');

    % solve the equilibrium
    eqm_cf1 = solve_eqm_cf1_outer(param, const, eqm);
       
    % calculate vars for each firm type    
    firm_cf1 = cal_firm_vars(param, const, eqm_cf1);
    
    % counterfactual changes
    ge_cf1 = cal_chg_ge(eqm, firm, eqm_cf1, firm_cf1);       
  

    
 %% Output tables and figures
diary off

    % create folder
    mkdir('../../output/tables') 

    %print_table_param(param, '../../output/tables/importmodel_param.tex')
    print_table_param(param, '../../output/tables/TableA22.tex')

    %print_table_model_fit(data, model, bartik, '../../output/tables/Tables/importmodel_fit.tex')  
    print_table_model_fit(data, model, bartik, '../../output/tables/TableA23.tex')  

    %print_table_cf_by_quintile(ge_cf1, '../../output/tables/importmodel_cf1.tex')    
    print_table_cf_by_quintile(ge_cf1, '../../output/tables/TableA24.tex')    



    